﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web;
using System.Web.Security;
using common;
using logistical.Models;

namespace logistical.Controllers
{
    public class loginController : ApiController
    {
        [HttpGet]
        public object login(string username,string pwd)
        {
            var o = new logisticalEntities();
            if (o.sys_userinfo.Where(x => x.username == username || x.password == pwd).Count() == 1)
            {
                var p = o.sys_userinfo.Where(x => x.username == username || x.password == pwd).FirstOrDefault();

                // 加密UserInfo
                UserInfo user = new UserInfo();
                user.useruid = p.id;
                user.username = p.username;
                user.role = p.role;
                user.userhostaddress = HttpContext.Current.Request.UserHostAddress;

                if (o.base_employee.Where(x => x.id == p.account).Count() == 1) {
                    var q = o.base_employee.Where(x => x.id == p.account).FirstOrDefault();
                    user.code = q.code;
                    user.name = q.name;
                    user.account = q.id;
                }
                if (o.base_company.Where(x => x.id == p.account).Count() == 1)
                {
                    var q = o.base_company.Where(x => x.id == p.account).FirstOrDefault();
                    user.code = q.code;
                    user.name = q.name;
                    user.account = q.id;
                }

                // 设置Ticket信息
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1, user.username, DateTime.Now, DateTime.Now.AddMinutes(20), false, CurUser.Encrypt(user));

                // 加密验证票据
                string strTicket = FormsAuthentication.Encrypt(ticket);

                // 使用新userdata保存cookie
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strTicket);
                cookie.Expires = ticket.Expiration;
                HttpContext.Current.Response.Cookies.Add(cookie);
                return new { msg = "", code = "", url = "index.html" };
            }
            return new { msg = "error", code = "", url = "" };
        }

        [HttpGet]
        public object loginOut()
        {
            FormsAuthentication.SignOut();
            return new { msg = "loginOut" };
        }
    }
}
